//
//  GWMicphoneViewController.m
//  Glowalker
//
//  Created by Harvey on 2017/10/5.
//  Copyright © 2017年 Haley. All rights reserved.
//

#import "GWMicphoneViewController.h"
#import "GWBarAnimationView.h"
#import "BluetoothManager.h"
#import "NSString+QCExtension.h"

#import <AVFoundation/AVFoundation.h>

@interface GWMicphoneViewController ()

@property (strong, nonatomic) GWBarAnimationView            *barAnimationView;

@property (strong, nonatomic) UIButton            *startBtn;
@property (strong, nonatomic) UIButton            *stopBtn;

//录音音量检测
@property (nonatomic,strong) AVAudioRecorder *recorder;

@property (nonatomic,strong) NSTimer *levelTimer;

@end

@implementation GWMicphoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = showText(@"麦克风律动");
    
    [self initSubViews];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord error:nil];
    //关闭远程事件
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
}

- (void)initSubViews
{
    CGFloat paddingH = 60;
    CGFloat remainH = kHeight - 64-(kWidth-120)-80;
    if (remainH < paddingH * 3) {
        paddingH = remainH / 3;
    }
    
    CGFloat topW = kWidth-120;
    UIImageView *topImageView = [[UIImageView alloc] initWithFrame:CGRectMake(60, paddingH, topW, topW)];
    topImageView.image = [UIImage imageNamed:@"mic_bg"];
    [self.view addSubview:topImageView];
    
    CGFloat barW = topW * 0.7;
    self.barAnimationView = [[GWBarAnimationView alloc] initWithFrame:CGRectMake(0, 0, barW, barW)];
    self.barAnimationView.center = CGPointMake(topW*0.5, topW*0.5);
    self.barAnimationView.backgroundColor = [UIColor clearColor];
    [topImageView addSubview:self.barAnimationView];
    
    UIButton *startBtn = [[UIButton alloc] initWithFrame:CGRectMake((kWidth-80)*0.5, kHeight-64-80-paddingH, 80, 80)];
    [startBtn setBackgroundImage:[UIImage imageNamed:@"mic_bg"] forState:UIControlStateNormal];
    [startBtn setTitle:showText(@"开始") forState:UIControlStateNormal];
    startBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [startBtn addTarget:self action:@selector(startRecord) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:startBtn];
    self.startBtn = startBtn;
    
    UIButton *stopBtn = [[UIButton alloc] initWithFrame:CGRectMake((kWidth-80)*0.5, kHeight-64-80-paddingH, 80, 80)];
    [stopBtn setBackgroundImage:[UIImage imageNamed:@"mic_bg"] forState:UIControlStateNormal];
    [stopBtn setTitle:showText(@"停止") forState:UIControlStateNormal];
    stopBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [stopBtn addTarget:self action:@selector(stopRecord) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:stopBtn];
    self.stopBtn = stopBtn;
    self.stopBtn.hidden = YES;
}

- (AVAudioRecorder *)recorder{
    if (!_recorder) {
        /* 不需要保存录音文件 */
        NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
        
        NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [NSNumber numberWithFloat: 44100.0], AVSampleRateKey,
                                  [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
                                  [NSNumber numberWithInt: 2], AVNumberOfChannelsKey,
                                  [NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey,
                                  nil];
        
        NSError *error;
        _recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
        if (self.recorder)
        {
            [_recorder prepareToRecord];
            _recorder.meteringEnabled = YES;
            [_recorder record];
            self.levelTimer = [NSTimer scheduledTimerWithTimeInterval: 0.2 target: self selector: @selector(levelTimerCallback:) userInfo: nil repeats: YES];
        }
        else
        {
            NSLog(@"%@", [error description]);
        }
        
    }
    return _recorder;
}

- (void)levelTimerCallback:(NSTimer *)timer {
    [self.recorder updateMeters];
    
    float   level;                // The linear 0.0 .. 1.0 value we need.
    float   minDecibels = -80.0f; // Or use -60dB, which I measured in a silent room.
    float   decibels    = [self.recorder averagePowerForChannel:0];
    
    if (decibels < minDecibels) {
        level = 0.0f;
    } else if (decibels >= 0.0f) {
        level = 1.0f;
    } else {
        float   root            = 2.0f;
        float   minAmp          = powf(10.0f, 0.05f * minDecibels);
        float   inverseAmpRange = 1.0f / (1.0f - minAmp);
        float   amp             = powf(10.0f, 0.05f * decibels);
        float   adjAmp          = (amp - minAmp) * inverseAmpRange;
        
        level = powf(adjAmp, 1.0f / root);
    }
    
    NSArray *randomColors = @[@"FF0000",@"FF8000",@"FFFF00",@"00FF00",@"00FFFF",@"0000FF",@"8000FF"];
    
    int per = level*100;
    NSLog(@"level:%f----%f",level,decibels);
    NSString *string = [NSString ToHex:per];
    NSString *colors = randomColors[arc4random_uniform(7)];
    NSString *hexColor = [NSString stringWithFormat:@"01%@%@",colors,string];
    [[BluetoothManager standardManager] writCommad:hexColor];
//    [[NSUserDefaults standardUserDefaults]setObject:hexColor forKey:@"lastCommit"];
//    [[NSUserDefaults standardUserDefaults]synchronize];
    
    self.barAnimationView.scale = level * 1000;
}

#pragma mark - btn click events
- (void)startRecord
{
    [self recorder];
    
    self.startBtn.hidden = YES;
    self.stopBtn.hidden = NO;
    self.barAnimationView.hidden = NO;
}

- (void)stopRecord
{
    [self.recorder stop];
    self.recorder = nil;
    
    [self.levelTimer invalidate];
    self.levelTimer = nil;
    
    self.startBtn.hidden = NO;
    self.stopBtn.hidden = YES;
    self.barAnimationView.hidden = YES;
}

@end
